<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item >系统管理</el-breadcrumb-item>
      <el-breadcrumb-item >用户管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="formInline" class="user-search">
      <el-form-item label="搜索：">
        <el-select
          clearable
          size="small"
          v-model="formInline.storeid"
          placeholder="请选择仓库"
        >
          <el-option
            v-for="item in this.stores"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="">
        <el-input
          size="small"
          v-model="formInline.uname"
          placeholder="输入用户名"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          size="small"
          type="primary"
          icon="el-icon-search"
          @click="search"
          >搜索</el-button
        >
        <el-button
          size="small"
          type="primary"
          icon="el-icon-plus"
          @click="handleEdit()"
          >添加</el-button
        >
        <el-button
          size="small"
          type="primary"
          icon="el-icon-printer"
          v-print="'#pdfDom'"
          >打印</el-button
        >
        <el-button size="small" type="primary" icon="el-icon-download"
          >导出</el-button
        >
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table
      id="pdfDom"
      size="small"
      :data="userData"
      highlight-current-row
      v-loading="loading"
      border
      element-loading-text="拼命加载中"
      style="width: 100%"
    >
      <el-table-column align="center" sortable prop="id" label="ID" width="80">
      </el-table-column>
      <el-table-column
        align="center"
        sortable
        prop="uname"
        label="用户名"
        width="110"
      >
      </el-table-column>
      <el-table-column
        align="center"
        sortable
        prop="email"
        label="登录邮箱"
        width="150"
      >
      </el-table-column>
      <el-table-column
        align="center"
        sortable
        prop="sex"
        label="性别"
        width="80"
      >
      </el-table-column>
      <el-table-column
        align="center"
        sortable
        prop="role"
        label="权限"
        width="140"
      >
      </el-table-column>
      <el-table-column
        align="center"
        sortable
        prop="storeName"
        label="所属仓库"
        min-width="110"
      >
      </el-table-column>
      <el-table-column
        align="center"
        sortable
        prop="phone"
        label="手机"
        min-width="110"
      >
      </el-table-column>
      <el-table-column
        align="center"
        sortable
        :default-sort="{ prop: 'entryDate', order: 'descending' }"
        prop="entryDate"
        label="入职时间"
        min-width="90"
      >
        <!-- 格式化时间
        <template slot-scope="scope">
          <div>{{ scope.row.editTime | timestampToTime }}</div>
        </template> -->
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="230">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="danger"
            @click="deleteUser(scope.$index, scope.row)"
            >删除</el-button
          >
          <el-button
            size="mini"
            type="success"
            @click="resetpwd(scope.$index, scope.row)"
            >重置密码</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination
      v-bind:child-msg="pageparm"
      @callFather="callFather"
    ></Pagination>
    <!-- 编辑界面 -->
    <el-dialog
      :title="title"
      :visible.sync="editFormVisible"
      width="30%"
      @click="closeDialog('edit')"
    >
      <el-form
        label-width="80px"
        ref="editForm"
        :model="editForm"
        :rules="rules"
      >
        <el-form-item label="用户名" prop="uname">
          <el-input
            size="small"
            v-model="editForm.uname"
            auto-complete="off"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item v-show="this.editoradd" label="邮箱" prop="email">
          <el-input
            size="small"
            v-model="editForm.email"
            auto-complete="off"
            placeholder="请输入邮箱"
          ></el-input>
        </el-form-item>
        <el-form-item v-show="this.editoradd" label="密码" prop="pwd">
          <el-input
            type="password"
            v-model="editForm.pwd"
            auto-complete="off"
            placeholder="密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="authority">
          <el-select
            size="small"
            clearable
            v-model="editForm.authority"
            placeholder="请选择"
          >
            <el-option
              v-for="item in this.authoritys"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属仓库" prop="storeid">
          <el-select
            clearable
            size="small"
            v-model="editForm.storeid"
            placeholder="请选择"
          >
            <el-option
              v-for="item in this.stores"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input
            size="small"
            v-model="editForm.phone"
            placeholder="请输入手机号"
          ></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="editForm.sex">
            <el-radio label="男"></el-radio>
            <el-radio label="女"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="入职时间" prop="entryDate" style="width: 100%">
          <el-col :span="11">
            <el-date-picker
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="入职时间"
              v-model="editForm.entryDate"
            ></el-date-picker>
          </el-col>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog('edit')">取消</el-button>
        <el-button
          size="small"
          type="primary"
          :loading="loading"
          class="title"
          @click="submitForm('editForm')"
          >保存</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 导入请求方法
import {
  userList,
  userSave,
  userAdd,
  userDelete,
  userRepwd,
} from "../../api/sysMG";
import {
  validatePhone,
  validatePassword,
  validateUsername,
  validateEmail,
} from "../../utils/util";
import { getStroeItem, getRoleItem } from "../../api/basisMG";
import Pagination from "../../components/Pagination";
import print from "vue-print-nb";
export default {
  data() {
    return {
      loading: false, //是显示加载
      title: "编辑用户",
      editFormVisible: false, //控制编辑页面显示与隐藏
      // 编辑与添加
      editForm: {
        id: "",
        uname: "",
        authority: "",
        storeid: "",
        sex: "男",
        entryDate: "",
        email: "",
        phone: "",
        pwd: "",
      },
      // 编辑隐藏部分数据
      editoradd: true,
      // rules表单验证
      rules: {
        uname: [
          { required: true, validator: validateUsername, trigger: "blur" },
        ],
        email: [{ required: true, validator: validateEmail, trigger: "blur" }],
        pwd: [{ required: true, validator: validatePassword, trigger: "blur" }],
        phone: [{ required: true, validator: validatePhone, trigger: "blur" }],
        entryDate: [
          { required: true, message: "请输入入职时间", trigger: "blur" },
        ],
        sex: [{ required: true, message: "请选择性别", trigger: "blur" }],
        authority: [{ required: true, message: "请选择角色", trigger: "blur" }],
        storeid: [
          { required: true, message: "请选择所属仓库", trigger: "blur" },
        ],
      },
      // 请求数据参数
      formInline: {
        page: 1,
        size: 10,
      },
      // 仓库选择框数据源
      stores: [],
      // 角色选择框数据源
      authoritys: [],
      // 用户数据
      userData: [],
      // 重置密码提交对象
      resetpwdparams: {},
      // 分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 10,
        total: 10,
      },
    };
  },
  // 注册组件
  components: {
    Pagination,
    print,
  },
  /**
   * 数据发生改变
   */
  watch: {},
  /**
   * 创建完毕
   */
  created() {
    this.getdata(this.formInline);
    this.getSelectItem();
  },

  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {
    // 获取仓库和角色列表数据
    getSelectItem() {
      getStroeItem().then((res) => {
        if (res.status == 200) {
          this.stores = res.data;
        } else {
          this.$message({
            type: "info",
            message: "获取仓库列表失败,刷新页面试试",
          });
        }
      });
      getRoleItem().then((res) => {
        if (res.status == 200) {
          this.authoritys = res.data;
        } else {
          this.$message({
            type: "info",
            message: "获取角色列表失败,刷新页面试试",
          });
        }
      });
    },
    // 获取数据方法
    getdata(parameter) {
      this.loading = true;
      // 获取用户列表
      userList(parameter).then((res) => {
        this.loading = false;
        if (res.status == 200) {
          this.userData = res.data;
          // 分页赋值
          this.pageparm.currentPage = this.formInline.page;
          this.pageparm.pageSize = this.formInline.size;
          this.pageparm.total = res.count;
        } else {
          this.$message({
            type: "info",
            message: res.statusInfo.message,
          });
        }
      });
    },
    // 分页插件事件
    callFather(parm) {
      this.formInline.page = parm.currentPage;
      this.formInline.size = parm.pageSize;
      this.getdata(this.formInline);
    },
    //搜索事件
    search() {
      this.getdata(this.formInline);
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      this.editFormVisible = true;
      if (row != undefined && row != "undefined") {
        this.editoradd = false;
        this.title = "修改用户";
        this.editForm.id = row.id;
        this.editForm.uname = row.uname;
        if (row.role == "暂无") {
          this.editForm.authority = "";
        } else {
          this.editForm.authority = row.role;
        }
        if (row.storeName == "暂无") {
          this.editForm.storeid = "";
        } else {
          this.editForm.storeid = row.storeName;
        }
        this.editForm.sex = row.sex;
        this.editForm.entryDate = row.entryDate;
        this.editForm.email = row.email;
        this.editForm.phone = row.phone;
        this.editForm.pwd = "123456";
      } else {
        this.editoradd = true;
        this.title = "新增用户";
        this.editForm.id = "";
        this.editForm.uname = "";
        this.editForm.authority = "";
        this.editForm.storeid = "";
        this.editForm.sex = "";
        this.editForm.entryDate = "";
        this.editForm.email = "";
        this.editForm.phone = "";
        this.editForm.pwd = "";
      }
    },
    // 编辑保存提交方法
    submitForm(editData) {
      this.$refs[editData].validate((valid) => {
        if (valid) {
          // id为空则提交为添加
          if (this.editForm.id == "") {
            userAdd(this.editForm)
              .then((res) => {
                this.editFormVisible = false;
                this.loading = false;
                if (res.status == 201) {
                  this.getdata(this.formInline);
                  this.$message({
                    type: "success",
                    message: "添加用户成功！",
                  });
                } else {
                  if (res.status == 304) {
                    this.$message({
                      type: "info",
                      message: "邮箱已存在！",
                    });
                  } else {
                    this.$message({
                      type: "error",
                      message: res.statusInfo.message,
                    });
                  }
                }
              })
              .catch((err) => {
                this.editFormVisible = false;
                this.loading = false;
                this.$message.error("保存失败，请稍后再试！");
              });
          } else {
            userSave(this.editForm)
              .then((res) => {
                this.editFormVisible = false;
                this.loading = false;
                if (res.status == 201) {
                  this.getdata(this.formInline);
                  this.$message({
                    type: "success",
                    message: "用户信息保存成功！",
                  });
                } else {
                  this.$message({
                    type: "info",
                    message: res.msg,
                  });
                }
              })
              .catch((err) => {
                this.editFormVisible = false;
                this.loading = false;
                this.$message.error("保存失败，请稍后再试！");
              });
          }
        } else {
          return false;
        }
      });
    },
    // 关闭编辑、增加弹出框
    closeDialog(dialog) {
      if (dialog == "edit") {
        this.editFormVisible = false;
      }
    },
    // 删除用户
    deleteUser(index, row) {
      this.$confirm("确定要删除吗?", "信息", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 删除
          userDelete({ id: row.id })
            .then((res) => {
              if (res.status == 204) {
                this.$message({
                  type: "success",
                  message: "用户数据已删除!",
                });
                this.getdata(this.formInline);
              } else {
                this.$message({
                  type: "error",
                  message: res.statusInfo.message,
                });
              }
            })
            .catch((err) => {
              this.loading = false;
              this.$message.error("数据删除失败，请稍后再试！");
            });
        })
        .catch(() => {});
    },
    // 重置密码
    resetpwd(index, row) {
      this.$confirm("确定密码重置为邮箱吗?", "信息", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.resetpwdparams = {
            id: row.id,
            email: row.email,
          };
          userRepwd(this.resetpwdparams)
            .then((res) => {
              if (res.status == 201) {
                this.$message({
                  type: "success",
                  message: "重置密码成功！",
                });
              } else {
                this.$message({
                  type: "info",
                  message: "重置密码失败，请联系管理员寻求帮助",
                });
              }
            })
            .catch((err) => {
              this.loading = false;
              this.$message.error("重置密码失败，请稍后再试！");
            });
        })
        .catch(() => {});
    },
  },
};
</script>

<style scoped>
.user-search {
  margin-top: 20px;
}
</style>

 